<template>
  <div class="admin-dashboard">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <stats-card
          :icon="User"
          title="总用户数"
          :value="stats.totalUsers || 0"
          :trend="stats.userTrend"
          color="#409EFF"
        />
      </el-col>
      <el-col :span="6">
        <stats-card
          :icon="Calendar"
          title="今日预约"
          :value="stats.todayAppointments || 0"
          :trend="stats.appointmentTrend"
          color="#67C23A"
        />
      </el-col>
      <el-col :span="6">
        <stats-card
          :icon="UserFilled"
          title="活跃用户"
          :value="stats.activeUsers || 0"
          :trend="16"
          color="#E6A23C"
        />
      </el-col>
      <el-col :span="6">
        <stats-card
          :icon="Monitor"
          title="系统负载"
          :value="systemLoadText"
          :color="systemLoadColor"
          :trend="undefined"
        />
      </el-col>
    </el-row>

    <!-- 预约趋势图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>预约趋势</span>
              <el-radio-group v-model="timeRange" size="small">
                <el-radio-button label="week">近7天</el-radio-button>
                <el-radio-button label="month">近30天</el-radio-button>
                <el-radio-button label="year">近365天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="appointmentTrendChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 咨询师月度收入图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>咨询师月度收入</span>
              <el-date-picker
                v-model="incomeMonth"
                type="month"
                format="YYYY年MM月"
                placeholder="选择月份"
                size="small"
              />
            </div>
          </template>
          <div ref="counselorIncomeChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据分析和系统日志 -->
    <el-row :gutter="20" class="analysis-row">
      <!-- 左侧数据分析 -->
      <el-col :span="16">
        <el-card class="analysis-card">
          <template #header>
            <div class="card-header">
              <span>数据分析</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="chart-container">
                <div class="chart-title">登录地理分布</div>
                <div ref="geoDistributionChart" class="pie-chart"></div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="chart-container">
                <div class="chart-title">设备类型分布</div>
                <div ref="deviceDistributionChart" class="pie-chart"></div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="chart-container">
                <div class="chart-title">咨询类型占比</div>
                <div ref="consultationTypeChart" class="pie-chart"></div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="chart-container">
                <div class="chart-title">问题类型分布</div>
                <div ref="problemTypeChart" class="pie-chart"></div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 右侧系统日志 -->
      <el-col :span="8">
        <el-card class="analysis-card">
          <template #header>
            <div class="card-header">
              <span>系统日志</span>
            </div>
          </template>
          <el-scrollbar height="860px">
            <el-timeline>
              <el-timeline-item
                v-for="log in mergedLogs"
                :key="log.logType + '-' + log.id"
                :timestamp="formatDateTime(log.createTime)"
                :type="log.logType === 'register' ? (log.status === 'SUCCESS' ? 'success' : 'danger') : (log.status === 0 ? 'success' : 'danger')"
              >
                <template v-if="log.logType === 'register'">
                  {{ log.username }} 注册为{{ getRoleText(log.role) }}
                  <div class="log-detail">
                    <small>{{ log.browser }} - {{ log.os }}</small>
                    <small v-if="log.location">· {{ log.location }}</small>
                  </div>
                </template>
                <template v-else>
                  {{ log.username }} 从 {{ log.location || '未知' }} 
                  {{ log.status === 0 ? '成功' : '失败' }}登录系统
                  <div class="log-detail">
                    <small>{{ log.browser }} - {{ log.os }}</small>
                  </div>
                </template>
              </el-timeline-item>
            </el-timeline>
          </el-scrollbar>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts/core'
import { PieChart, LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { LabelLayout } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { 
  getLoginStats,
  getAppointmentTrend,
  getLoginGeoDistribution,
  getDeviceDistribution,
  getLoginLogs,
  getRegisterLogs,
  type LoginLog,
  type RegisterLog
} from '@/api/dashboard'
import StatsCard from '../dashboard/components/StatsCard.vue'
import SystemLoadCard from '../dashboard/components/SystemLoadCard.vue'
import type { LoginStatsVO } from '@/api/dashboard'
import { getSystemLoad } from '@/api/system'
import type { SystemLoadVO } from '@/api/system'
import { User, Calendar, UserFilled, Monitor } from '@element-plus/icons-vue'
import { Plus } from '@element-plus/icons-vue'
import { formatTime } from '@/utils/time'
import { getCounselorIncome } from '@/api/analysis'
import type { CounselorIncomeData } from '@/types/analysis'
import { 
  getConsultationTypeStats,
  getProblemTypeDistribution
} from '@/api/analysis'

// 注册必需的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  PieChart,
  LineChart,
  BarChart,
  CanvasRenderer,
  LabelLayout
])

// 定义接口
interface DataCard {
  title: string
  value: number | string
  icon: string
  color: string
  trend: 'up' | 'down'
  change: number
}

// 添加地理分布和设备分布数据的接口定义
interface DistributionItem {
  name: string
  value: {
    count: number
    avg_duration: number
    location?: string
    device_type?: string
  }
}

interface Stats {
  totalUsers: number
  todayAppointments: number
  activeUsers: number
  userTrend: number
  appointmentTrend: number
}

// 在 script setup 部分的接口定义区域添加
interface MergedLoginLog extends LoginLog {
  logType: 'login'
}

interface MergedRegisterLog extends RegisterLog {
  logType: 'register'
}

type MergedLog = MergedLoginLog | MergedRegisterLog

const router = useRouter()

// 数据状态
const dataCards = ref<DataCard[]>([])
const loginLogs = ref<LoginLog[]>([])
const registerLogs = ref<RegisterLog[]>([])
const timeRange = ref<'week' | 'month' | 'year'>('week')
const systemLoadData = ref<SystemLoadVO>({} as SystemLoadVO)
const stats = ref<Stats>({
  totalUsers: 0,
  todayAppointments: 0,
  activeUsers: 0,
  userTrend: 0,
  appointmentTrend: 0
})

// 图表实例
let appointmentTrendInstance: echarts.ECharts | null = null
let geoDistributionInstance: echarts.ECharts | null = null
let deviceDistributionInstance: echarts.ECharts | null = null
let consultationTypeInstance: echarts.ECharts | null = null
let problemTypeInstance: echarts.ECharts | null = null
let counselorIncomeInstance: echarts.ECharts | null = null

const appointmentTrendChart = ref<HTMLElement>()
const geoDistributionChart = ref<HTMLElement>()
const deviceDistributionChart = ref<HTMLElement>()
const consultationTypeChart = ref<HTMLElement>()
const problemTypeChart = ref<HTMLElement>()
const counselorIncomeChart = ref<HTMLElement>()
const incomeMonth = ref<Date>(new Date())
const refreshTimer = ref<number | null>(null)

// 计算系统状态显示

// 计算系统状态颜色

// 计算系统负载显示文本
const systemLoadText = computed(() => {
  if (!systemLoadData.value.cpuUsage) return '0%'
  return `${Math.round(systemLoadData.value.cpuUsage)}%`
})

// 计算系统负载颜色
const systemLoadColor = computed(() => {
  const cpuUsage = systemLoadData.value.cpuUsage || 0
  if (cpuUsage >= 90) return '#F56C6C'
  if (cpuUsage >= 70) return '#E6A23C'
  return '#67C23A'
})

// 窗口大小变化处理函数
const resizeHandler = () => {
  appointmentTrendInstance?.resize()
  geoDistributionInstance?.resize()
  deviceDistributionInstance?.resize()
  consultationTypeInstance?.resize()
  problemTypeInstance?.resize()
  counselorIncomeInstance?.resize()
}

// 在setup函数顶层调用生命周期钩子
onUnmounted(() => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
  }
  window.removeEventListener('resize', resizeHandler)
  appointmentTrendInstance?.dispose()
  geoDistributionInstance?.dispose()
  deviceDistributionInstance?.dispose()
  consultationTypeInstance?.dispose()
  problemTypeInstance?.dispose()
})

// 初始化函数
onMounted(async () => {
  console.log('组件挂载开始')
  await nextTick()
  console.log('DOM更新完成')
  
  // 加载数据
  console.log('开始加载数据')
  await initData()
  console.log('数据加载完成')

  // 等待DOM更新
  await nextTick()
  
  // 初始化图表
  if (geoDistributionChart.value && !geoDistributionInstance) {
    console.log('初始化地理分布图表')
    geoDistributionInstance = echarts.init(geoDistributionChart.value)
    await loadGeoDistribution()
  }
  
  if (deviceDistributionChart.value && !deviceDistributionInstance) {
    console.log('初始化设备分布图表')
    deviceDistributionInstance = echarts.init(deviceDistributionChart.value)
    await loadDeviceDistribution()
  }
  
  if (appointmentTrendChart.value && !appointmentTrendInstance) {
    console.log('初始化趋势图表')
    appointmentTrendInstance = echarts.init(appointmentTrendChart.value)
    await loadAppointmentTrend()
  }
  
  if (consultationTypeChart.value && !consultationTypeInstance) {
    console.log('初始化咨询类型分布图表')
    consultationTypeInstance = echarts.init(consultationTypeChart.value)
    await loadConsultationType()
  }
  
  if (problemTypeChart.value && !problemTypeInstance) {
    console.log('初始化问题类型分布图表')
    problemTypeInstance = echarts.init(problemTypeChart.value)
    await loadProblemType()
  }
  
  if (counselorIncomeChart.value && !counselorIncomeInstance) {
    console.log('初始化咨询师月度收入图表')
    counselorIncomeInstance = echarts.init(counselorIncomeChart.value)
    await loadCounselorIncome()
  }
  
  // 设置定时刷新
  refreshTimer.value = window.setInterval(initData, 5 * 60 * 1000)
  
  // 监听窗口大小变化
  window.addEventListener('resize', resizeHandler)

  await fetchSystemLoad()
  // 每30秒刷新一次系统负载数据
  setInterval(() => {
    fetchSystemLoad()
  }, 30000)
})

// 日期格式化函数
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 初始化数据
const initData = async () => {
  await Promise.all([
    loadDashboardStats(),
    loadLoginLogs(),
    loadRegisterLogs()
  ])
}

// 加载统计数据
const loadDashboardStats = async () => {
  try {
    const { data } = await getLoginStats()
    dataCards.value = [
      {
        title: '总用户数',
        value: data.totalUsers,
        icon: 'User',
        color: '#409EFF',
        trend: data.userTrend > 0 ? 'up' : 'down',
        change: Math.abs(data.userTrend)
      },
      {
        title: '今日预约',
        value: data.todayAppointments || 0,
        icon: 'Calendar',
        color: '#67C23A',
        trend: 'up',
        change: 12
      },
      {
        title: '活跃用户',
        value: data.activeUsers || 0,
        icon: 'Message',
        color: '#E6A23C',
        trend: 'up',
        change: 16
      },
      {
        title: '系统负载',
        value: data.systemLoad || '正常',
        icon: 'Setting',
        color: '#909399',
        trend: 'down',
        change: 8
      }
    ]
    stats.value = {
      totalUsers: data.totalUsers,
      todayAppointments: data.todayAppointments || 0,
      activeUsers: data.activeUsers || 0,
      userTrend: data.userTrend,
      appointmentTrend: data.appointmentTrend
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载登录日志
const loadLoginLogs = async () => {
  try {
    const { data } = await getLoginLogs()
    loginLogs.value = data
  } catch (error) {
    console.error('加载登录日志失败:', error)
  }
}

// 加载注册日志
const loadRegisterLogs = async () => {
  try {
    const { data } = await getRegisterLogs()
    registerLogs.value = data
  } catch (error) {
    console.error('加载注册日志失败:', error)
  }
}

// 加载预约趋势
const loadAppointmentTrend = async () => {
  try {
    const days = timeRange.value === 'week' ? 7 : timeRange.value === 'month' ? 30 : 365
    const { data } = await getAppointmentTrend(days)
    
    if (appointmentTrendInstance) {
      appointmentTrendInstance.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: data.dates,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          minInterval: 1
        },
        series: [{
          data: data.counts,
          type: 'line',
          smooth: true,
          areaStyle: {
            opacity: 0.3
          },
          itemStyle: {
            color: '#409EFF'
          }
        }]
      })
    }
  } catch (error) {
    console.error('加载预约趋势失败:', error)
  }
}

// 加载地理分布数据
const loadGeoDistribution = async () => {
  try {
    const { data } = await getLoginGeoDistribution()
    const chartData = (data as DistributionItem[]).map(item => ({
      name: item.name || '未知地区',
      value: item.value.count
    }))
    
    if (geoDistributionChart.value) {
      if (!geoDistributionInstance) {
        geoDistributionInstance = echarts.init(geoDistributionChart.value)
      }
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: '10%',
          itemWidth: 10,
          itemHeight: 10,
          textStyle: {
            fontSize: 12,
            padding: [3, 15, 3, 15]
          },
          itemGap: 25,
          width: '90%'
        },
        series: [{
          type: 'pie',
          radius: ['35%', '65%'],
          center: ['50%', '45%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10
          },
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}\n{c} ({d}%)',
            lineHeight: 14,
            padding: [0, 0, 0, 0],
            fontSize: 11
          },
          labelLine: {
            show: true,
            length: 15,
            length2: 20,
            smooth: false
          },
          data: chartData
        }]
      }
      geoDistributionInstance.setOption(option, true)
    }
  } catch (error) {
    console.error('加载地理分布数据失败:', error)
  }
}

// 加载设备分布数据
const loadDeviceDistribution = async () => {
  try {
    const { data } = await getDeviceDistribution()
    const chartData = (data as DistributionItem[]).map(item => ({
      name: item.name || '未知设备',
      value: item.value.count
    }))
    
    if (deviceDistributionChart.value) {
      if (!deviceDistributionInstance) {
        deviceDistributionInstance = echarts.init(deviceDistributionChart.value)
      }
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: '10%',
          itemWidth: 10,
          itemHeight: 10,
          textStyle: {
            fontSize: 11,
            padding: [3, 15, 3, 15]
          },
          itemGap: 25,
          width: '90%'
        },
        series: [{
          name: '设备分布',
          type: 'pie',
          radius: ['35%', '65%'],
          center: ['50%', '45%'],
          avoidLabelOverlap: true,
          label: {
            show: true,
            position: 'outside',
            fontSize: 11,
            lineHeight: 14,
            formatter: '{b}\n{c} ({d}%)',
            padding: [2, 4, 2, 4]
          },
          labelLine: {
            show: true,
            length: 10,
            length2: 15,
            maxSurfaceAngle: 80
          },
          data: chartData
        }]
      }
      deviceDistributionInstance.setOption(option, true)
    }
  } catch (error) {
    console.error('加载设备分布数据失败:', error)
  }
}

// 获取系统负载数据
const fetchSystemLoad = async () => {
  try {
    const { data } = await getSystemLoad()
    systemLoadData.value = data
  } catch (error) {
    console.error('获取系统负载数据失败:', error)
  }
}

// 页面跳转
const goToLoginLog = () => {
  router.push('/system/login-log')
}

// 监听时间范围变化
watch(timeRange, () => {
  loadAppointmentTrend()
})

const getRoleText = (role: string) => {
  const roleMap: Record<string, string> = {
    'student': '学生',
    'counselor': '咨询师',
    'admin': '管理员'
  }
  return roleMap[role] || role
}

// 修改计算属性的类型定义
const mergedLogs = computed<MergedLog[]>(() => {
  const loginLogsWithType: MergedLoginLog[] = loginLogs.value.map(log => ({
    ...log,
    logType: 'login'
  }))
  const registerLogsWithType: MergedRegisterLog[] = registerLogs.value.map(log => ({
    ...log,
    logType: 'register'
  }))
  return [...loginLogsWithType, ...registerLogsWithType]
    .sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())
})

// 加载咨询类型分布
const loadConsultationType = async () => {
  try {
    const { data } = await getConsultationTypeStats()
    
    if (consultationTypeInstance) {
      consultationTypeInstance.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: '10%',
          data: ['AI咨询', '普通咨询']
        },
        series: [{
          name: '咨询类型',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}\n{c}次 ({d}%)'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          data: [
            { value: data.aiCount, name: 'AI咨询' },
            { value: data.normalCount, name: '普通咨询' }
          ]
        }]
      })
    }
  } catch (error) {
    console.error('加载咨询类型分布失败:', error)
  }
}

// 加载问题类型分布
const loadProblemType = async () => {
  try {
    const { data } = await getProblemTypeDistribution()
    
    if (problemTypeInstance) {
      const chartData = data.distribution.map(item => ({
        name: item.type,
        value: Number(item.count)
      }))
      
      problemTypeInstance.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}次 ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: '10%',
          data: data.distribution.map(item => item.type)
        },
        series: [{
          name: '问题类型',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}\n{c}次 ({d}%)'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          data: chartData
        }]
      })
    }
  } catch (error) {
    console.error('加载问题类型分布失败:', error)
  }
}

// 修改loadCounselorIncome函数
const loadCounselorIncome = async () => {
  try {
    // 将Date对象转换为YYYY-MM格式的字符串
    const month = incomeMonth.value ? 
      incomeMonth.value.toISOString().slice(0, 7) : undefined
    
    const { data } = await getCounselorIncome({ month })
    
    if (counselorIncomeInstance) {
      counselorIncomeInstance.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params: any) => {
            const data = params[0]
            const counselor = data.data
            return `
              <div style="padding: 3px;">
                <div style="margin-bottom: 5px;">${counselor.counselorName}</div>
                <div>月收入：¥${counselor.income}</div>
                <div>咨询次数：${counselor.appointmentCount}次</div>
                <div>平均评分：${counselor.rating}分</div>
              </div>
            `
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.counselorName),
          axisLabel: {
            interval: 0,
            rotate: 0
          }
        },
        yAxis: {
          type: 'value',
          name: '月收入(元)',
          axisLabel: {
            formatter: '{value}'
          }
        },
        series: [{
          name: '月收入',
          type: 'bar',
          data: data.map(item => ({
            value: item.income,
            counselorName: item.counselorName,
            appointmentCount: item.appointmentCount,
            rating: item.rating
          })),
          barWidth: '40%',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#2378f7' },
                { offset: 0.7, color: '#2378f7' },
                { offset: 1, color: '#83bff6' }
              ])
            }
          },
          label: {
            show: true,
            position: 'top',
            formatter: '¥{@value}'
          }
        }]
      })
    }
  } catch (error) {
    console.error('加载咨询师月度收入数据失败:', error)
  }
}

// 监听月份变化
watch(incomeMonth, () => {
  loadCounselorIncome()
})
</script>

<style lang="scss" scoped>
.admin-dashboard {
  padding: 20px;

  :deep(.appointment-trend-chart) {
    height: 300px !important;
    margin: 0 !important;
  }

  .chart-row {
    margin-top: 20px;
    
    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .chart {
        height: 300px !important;
        width: 100%;
        margin: 0 !important;
      }
    }
  }

  .analysis-row {
    margin-top: 20px;

    .analysis-card {
      height: 920px;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .chart-container {
        margin-bottom: 20px;

        .chart-title {
          font-size: 16px;
          font-weight: bold;
          margin-bottom: 10px;
          text-align: center;
        }

        .pie-chart {
          height: 380px;
          width: 100%;
        }
      }
    }
  }

  .log-detail {
    margin-top: 5px;
    color: #909399;
    font-size: 12px;

    small {
      margin-right: 10px;
    }
  }
}
</style> 